package eabnp.eflow.client.impl.local;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import java.util.List;

import eabnp.basic.result.GResult;
import eabnp.basic.result.IResult;
import eabnp.basic.util.ClassUtil;
import eabnp.eflow.client.IEFlowClient;

public class EFlowClientRmi extends UnicastRemoteObject implements IEFlowClientRmi {

	private static final long serialVersionUID = 2179256148794108742L;

	private String name;

	public EFlowClientRmi(String name) throws RemoteException {
		this.name = name;
	}

	private IEFlowClient getClient() {
		GResult gr = ClassUtil.newInstanceOfClass("eabnp.eflow.client.impl.local.EFlowClientLocal");
		return (IEFlowClient) gr.getResultObject();
	}

	@Override
	public IResult Exec(String method, Object... paras) throws RemoteException {
		IEFlowClient client = this.getClient();
		IResult rs = null;
		List<Class<?>> c = new ArrayList<>();
		try {
			if (paras != null) {
				for (Object o : paras) {
					if(o!=null){
						if(o.getClass().equals(Integer.class))
							c.add(int.class);
						else
							c.add(o.getClass());
					}else{
						c.add(String.class);
					}
					
				}
			}
			
			Method m = null;
			if (c.isEmpty()) {
				m = client.getClass().getMethod(method);
			} else {
				m = client.getClass().getMethod(method, c.toArray(new Class[paras.length]));
			}
			rs = (IResult) m.invoke(client, paras);
		} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
			e.printStackTrace();
		}
		return rs;
	}
}
